package com.chuanye.jiguangimdemo.fragments;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.chuanye.jiguangimdemo.R;
import com.chuanye.jiguangimdemo.activitys.FriendInfoActivity;
import com.chuanye.jiguangimdemo.activitys.GroupActivity;
import com.chuanye.jiguangimdemo.activitys.SearchContactsActivity;
import com.chuanye.jiguangimdemo.activitys.SearchForAddFriendActivity;
import com.chuanye.jiguangimdemo.activitys.VerificationMessageActivity;
import com.chuanye.jiguangimdemo.adapters.ContactAdapter;
import com.chuanye.jiguangimdemo.app.MyApplication;
import com.chuanye.jiguangimdemo.database.FriendRecommendEntry;
import com.chuanye.jiguangimdemo.database.UserEntry;
import com.chuanye.jiguangimdemo.entity.FriendInvitation;
import com.chuanye.jiguangimdemo.sharepreference.SharePreferenceManager;

import java.util.List;

import cn.jpush.im.android.api.ContactManager;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.callback.GetUserInfoCallback;
import cn.jpush.im.android.api.callback.GetUserInfoListCallback;
import cn.jpush.im.android.api.event.ContactNotifyEvent;
import cn.jpush.im.android.api.model.UserInfo;

/**
 * 联系人
 */
public class ContactFragment extends BaseFragment implements View.OnClickListener {

    private static final String TAG = "ContactFragment";
    private Context mContext;

    private ImageView contact_addfriend_iv;
    private LinearLayout contact_searchtitle_ll;
    private LinearLayout contact_verify_ll;
    private TextView contact_friend_verification_num_tv;
    private LinearLayout contact_group_ll;
    private TextView contact_group_verification_num_tv;
    private View contact_view_line_view;
    private ListView contact_lv;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_contact,null);
        mContext = getActivity();
        //订阅接收消息,子类只要重写onEvent就能收到消息
        JMessageClient.registerEventReceiver(getActivity());

        initView(view);

        initData();




        return view;

    }

    private void initData() {
        //获取好友列表
        ContactManager.getFriendList(new GetUserInfoListCallback() {
            @Override
            public void gotResult(int responseCode, String responseMessage, List<UserInfo> userInfoList) {
                if (responseCode == 0) {
                    //获取好友列表成功
                    MyApplication.mFriendInfoList = userInfoList;
                    ContactAdapter contactAdapter = new ContactAdapter(mContext,MyApplication.mFriendInfoList);
                    contact_lv.setAdapter(contactAdapter);

                } else {
                    //获取好友列表失败
                }
            }
        });

    }

    private void initView(View view) {
        //添加好友按钮
        contact_addfriend_iv = view.findViewById(R.id.contact_addfriend_iv);
        contact_addfriend_iv.setOnClickListener(this);
        //搜索按钮
        contact_searchtitle_ll = view.findViewById(R.id.contact_searchtitle_ll);
        contact_searchtitle_ll.setOnClickListener(this);
        //验证消息按钮
        contact_verify_ll = view.findViewById(R.id.contact_verify_ll);
        contact_verify_ll.setOnClickListener(this);
        //验证消息数量
        contact_friend_verification_num_tv = view.findViewById(R.id.contact_friend_verification_num_tv);
        //群组按钮
        contact_group_ll = view.findViewById(R.id.contact_group_ll);
        contact_group_ll.setOnClickListener(this);
        //群组消息数量
        contact_group_verification_num_tv = view.findViewById(R.id.contact_group_verification_num_tv);
        //view距离
        contact_view_line_view = view.findViewById(R.id.contact_view_line_view);

        //listview
        contact_lv = view.findViewById(R.id.contact_lv);


        contact_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String username = MyApplication.mFriendInfoList.get(position).getUserName();
                String appKey = MyApplication.mFriendInfoList.get(position).getAppKey();

                Intent intent = new Intent(mContext, FriendInfoActivity.class);
                intent.putExtra("fromContact", true);
                intent.putExtra(MyApplication.TARGET_ID, username);
                intent.putExtra(MyApplication.TARGET_APP_KEY, appKey);
                mContext.startActivity(intent);
            }
        });

    }


    public void onEvent(ContactNotifyEvent event){
        Log.i(TAG,"onEvent:"+event.getType());
        final UserEntry user = MyApplication.getUserEntry();
        Log.i(TAG,"接收好友邀请:"+"getUserEntry自己的用户名："+user.username);
        final String reason = event.getReason();
        final String username = event.getFromUsername();
        final String appKey = event.getfromUserAppKey();
        Log.i(TAG,"接收好友邀请:"+event.getType()+"来自用户名："+username+" ,添加理由："+reason+" ,appKey:"+appKey);
        if (event.getType() == ContactNotifyEvent.Type.invite_received){
            //如果同一个人申请多次,则只会出现一次;当点击进验证消息界面后,同一个人再次申请则可以收到
            if (MyApplication.forAddFriend.size() > 0) {//添加数据集合
                for (String forAdd : MyApplication.forAddFriend) {
                    if (forAdd.equals(username)) {
                        return;
                    } else {
                        MyApplication.forAddFriend.add(username);
                    }
                }
            } else {
                MyApplication.forAddFriend.add(username);
            }
            //请求获取用户信息
            JMessageClient.getUserInfo(username, appKey, new GetUserInfoCallback() {
                @Override
                public void gotResult(int status, String desc, UserInfo userInfo) {
                    Log.i(TAG,"请求获取用户信息:"+"状态码："+status + " ,返回内容："+desc + "用户名："+userInfo.getUserName());
                    if (status == 0) {
                        String name = userInfo.getNickname();
                        if (TextUtils.isEmpty(name)) {
                            name = userInfo.getUserName();
                        }
                        //数据库
                        FriendRecommendEntry entry = FriendRecommendEntry.getEntry(user, username, appKey);
                        if (null == entry) {
                            if (null != userInfo.getAvatar()) {
                                String path = userInfo.getAvatarFile().getPath();
                                entry = new FriendRecommendEntry(userInfo.getUserID(), username, userInfo.getNotename(), userInfo.getNickname(), appKey, path,
                                        name, reason, FriendInvitation.INVITED.getValue(), user, 0);
                            } else {
                                entry = new FriendRecommendEntry(userInfo.getUserID(), username, userInfo.getNotename(), userInfo.getNickname(), appKey, null,
                                        username, reason, FriendInvitation.INVITED.getValue(), user, 0);
                            }
                        } else {
                            entry.state = FriendInvitation.INVITED.getValue();
                            entry.reason = reason;
                        }
                        entry.save();
                        //收到好友请求数字 +1
                        Log.i(TAG,"收到好友请求数字:"+SharePreferenceManager.getCachedNewFriendNum());
                        int showNum = SharePreferenceManager.getCachedNewFriendNum() + 1;
                        //验证消息
                        contact_friend_verification_num_tv.setVisibility(View.VISIBLE);
                        if (showNum > 99){
                            contact_friend_verification_num_tv.setText("99+");
                        }else {
                            contact_friend_verification_num_tv.setText(String.valueOf(showNum));
                        }
                        Log.i(TAG,"收到好友请求数字+1:"+showNum);
                        SharePreferenceManager.setCachedNewFriendNum(showNum);
                    }
                }
            });
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.contact_addfriend_iv://添加好友按钮 标题栏加号添加好友
                Intent intent = new Intent(mContext, SearchForAddFriendActivity.class);
                mContext.startActivity(intent);
                break;
            case R.id.contact_searchtitle_ll://搜索按钮

                Intent intent2 = new Intent(mContext, SearchContactsActivity.class);
                mContext.startActivity(intent2);

                break;
            case R.id.contact_verify_ll://验证消息按钮
                Intent intent3 = new Intent(mContext, VerificationMessageActivity.class);
                mContext.startActivity(intent3);

                //消息清零
                SharePreferenceManager.setCachedNewFriendNum(0);
                MyApplication.forAddIntoGroup.clear();
                MyApplication.forAddFriend.clear();
                //红点隐藏
                contact_friend_verification_num_tv.setVisibility(View.GONE);
                break;
            case R.id.contact_group_ll://群组按钮

                Intent intent4 = new Intent(mContext, GroupActivity.class);
                mContext.startActivity(intent4);
                break;

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //注销消息接收
        JMessageClient.unRegisterEventReceiver(getActivity());
    }
}
